package com.jprocms.module.cms.controller.directive;

import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.module.infra.api.config.ConfigApi;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.Map;

/**
 * 配置数据 自定义标签
 *
 * @author jprocms
 */
public class ConfigDirective implements TemplateDirectiveModel {
    private static final String KEY = "key";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);
        String key = Directives.getString(params, KEY);
        CommonResult<String> configGetResult = configApi.getConfigValueByKey(key);
        loopVars[0] = env.getObjectWrapper().wrap(configGetResult.getData());
        body.render(env.getOut());
    }

    private final ConfigApi configApi;

    public ConfigDirective(ConfigApi configApi) {
        this.configApi = configApi;
    }
}
